package com.ruoyi.system.interAttr.attr;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.inter.mapper.SalePartnerMapper;
import com.ruoyi.system.interAttr.domain.GamesRes;
import com.ruoyi.system.interAttr.domain.InterAttrRes;
import com.ruoyi.system.interAttr.domain.InterServerRes;
import com.ruoyi.system.model.domain.SalePartner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class MONIXIZAIAttr implements AdapterAttr {
    @Autowired
    SalePartnerMapper salePartnerMapper;

    public static void main(String[] args) {
        String tokenBody = HttpRequest.get("http://jym.maimaizhanghao.com:7589/xizai?uname=15225247351&pwd=15225247351")
                .execute().body();
        JSONObject tokenJsonObject = JSONObject.parseObject(tokenBody);
        String authorization = tokenJsonObject.getString("token");
        System.out.println(authorization);
    }

    @Override
    public List<GamesRes> getGames(SalePartner salePartner) {
        String result = HttpRequest.get("https://www.xizai.com/trade/goodsApi/queryOpenCategory").execute().body();
        boolean isTrue = replaceToken(salePartner, result);
        if (isTrue) getGames(salePartner);
        JSONObject resJson = JSONObject.parseObject(result);
        List<JSONObject> jsonObjects = JSONObject.parseArray(resJson.getString("list"), JSONObject.class);
        List<GamesRes> gamesResList = new ArrayList<>();

        for (JSONObject jsonObject : jsonObjects) {
            GamesRes gamesRes = new GamesRes();
            String id = jsonObject.getString("categoryId");
            String title = jsonObject.getString("categoryName");
            gamesRes.setId(id);
            gamesRes.setGameName(title);
            gamesResList.add(gamesRes);
        }
        return gamesResList;
    }

    @Override
    public List<InterServerRes> getServer(String gameId, SalePartner salePartner) {
        // 区服拼接方式 id在前字段在后
        List<InterServerRes> interServerResList = new ArrayList<>();
        // gameId 为 2 是对接方王者荣耀的游戏 id
        if (gameId.equals("2")) {
            String checkCategoryToConfig = HttpRequest.get("https://www.xizai.com/trade/business/back/checkCategoryToConfig?categoryId=" + gameId)
                    .header("authorization", salePartner.getTwoOther())
                    .execute()
                    .body();
            boolean isTrue = replaceToken(salePartner, checkCategoryToConfig);
            if (isTrue) getServer(gameId, salePartner);
            JSONObject checkCategoryToConfigJson = JSONObject.parseObject(checkCategoryToConfig);
            String checkCategoryToConfigCode = checkCategoryToConfigJson.getString("code");
            if (checkCategoryToConfigCode.equals("0")) {
                List<JSONObject> configList = JSONObject.parseArray(checkCategoryToConfigJson.getString("configList"), JSONObject.class);
                for (JSONObject config : configList) {
                    InterServerRes interServerRes = new InterServerRes();
                    interServerRes.setId(config.getString("dateId") + "&area");
                    interServerRes.setName(config.getString("dateName"));
                    interServerRes.setUuid(UUID.randomUUID().toString());
                    interServerResList.add(interServerRes);
                }
            }
        } else {
            JSONObject gameAttribute = getGameAttribute(gameId, salePartner, true);
            if (ObjectUtil.isNotEmpty(gameAttribute)) {
                String fuwuqi = gameAttribute.getString("fuwuqi");
                JSONObject fuwuqiJson = new JSONObject();
                JSONObject childrenJson = new JSONObject();
                boolean isMontage = false;
                if (ObjectUtil.isNotEmpty(fuwuqi)) {
                    fuwuqiJson = JSONObject.parseObject(fuwuqi);
                    String children = fuwuqiJson.getString("children");
                    if (StringUtils.isNotEmpty(children)) {
                        childrenJson = JSONObject.parseObject(children);
                        isMontage = true;
                    }
                }
                if (!isMontage) {
                    String system = gameAttribute.getString("system");
                    if (ObjectUtil.isNotEmpty(system)) {
                        JSONObject systemJson = JSONObject.parseObject(system);
                        List<JSONObject> systemDictValueList = JSONObject.parseArray(systemJson.getString("dictValue"), JSONObject.class);
                        for (JSONObject systemDictValue : systemDictValueList) {
                            String sysFieldId = systemDictValue.getString("dictCode") + "&" + systemJson.getString("fieldIdentification");
                            String sysFieldName = systemDictValue.getString("dictValue");
                            InterServerRes sysInterServerRes = new InterServerRes();
                            sysInterServerRes.setId(sysFieldId);
                            sysInterServerRes.setName(sysFieldName);
                            sysInterServerRes.setUuid(UUID.randomUUID().toString());
                            // 下级
                            if (ObjectUtil.isNotEmpty(fuwuqiJson)) {
                                List<InterServerRes> fuwuqiInterServerResList = new ArrayList<>();
                                List<JSONObject> fuwuqiDictValueList = JSONObject.parseArray(fuwuqiJson.getString("dictValue"), JSONObject.class);
                                for (JSONObject fuwuqiDictValue : fuwuqiDictValueList) {
                                    // 服务器 id 上级字段名 + 字段code
                                    String fuwuqiFieldId = fuwuqiDictValue.getString("dictCode") + "&" + fuwuqiJson.getString("fieldIdentification");
                                    String fuwuqiFieldName = fuwuqiDictValue.getString("dictValue");
                                    InterServerRes fuwuqiInterServerRes = new InterServerRes();
                                    fuwuqiInterServerRes.setId(fuwuqiFieldId);
                                    fuwuqiInterServerRes.setName(fuwuqiFieldName);
                                    fuwuqiInterServerRes.setUuid(UUID.randomUUID().toString());
                                    fuwuqiInterServerResList.add(fuwuqiInterServerRes);
                                }
                                sysInterServerRes.setInterServerRes(fuwuqiInterServerResList);
                            }
                            interServerResList.add(sysInterServerRes);
                        }
                    }
                } else {
                    if (ObjectUtil.isNotEmpty(fuwuqiJson)) {
                        List<InterServerRes> fuwuqiInterServerResList = new ArrayList<>();
                        List<JSONObject> fuwuqiDictValueList = JSONObject.parseArray(fuwuqiJson.getString("dictValue"), JSONObject.class);
                        for (JSONObject fuwuqiDictValue : fuwuqiDictValueList) {
                            // 服务器 id 上级字段名 + 字段code
                            String fuwuqiFieldId = fuwuqiDictValue.getString("dictCode") + "&" + fuwuqiJson.getString("fieldIdentification");
                            String fuwuqiFieldName = fuwuqiDictValue.getString("dictValue");
                            InterServerRes fuwuqiInterServerRes = new InterServerRes();
                            fuwuqiInterServerRes.setId(fuwuqiFieldId);
                            fuwuqiInterServerRes.setName(fuwuqiFieldName);
                            fuwuqiInterServerRes.setUuid(UUID.randomUUID().toString());
                            // 是否需要拼接
                            List<JSONObject> childrenDictValueList = JSONObject.parseArray(childrenJson.getString("dictValue"), JSONObject.class);
                            for (JSONObject childrenDictValue : childrenDictValueList) {
                                InterServerRes childInterServerRes = new InterServerRes();
                                childInterServerRes.setId(childrenDictValue.getString("dictCode") + "&" + childrenJson.getString("fieldIdentification"));
                                childInterServerRes.setName(childrenDictValue.getString("dictValue"));
                                childInterServerRes.setUuid(UUID.randomUUID().toString());
                                fuwuqiInterServerResList.add(childInterServerRes);
                            }
                            fuwuqiInterServerRes.setInterServerRes(fuwuqiInterServerResList);
                            interServerResList.add(fuwuqiInterServerRes);
                        }
                    }
                }
            }
        }
        return interServerResList;
    }

    @Override
    public List<InterAttrRes> getPropety(String gameId, String type, SalePartner salePartner) {
        JSONObject gameAttribute = getGameAttribute(gameId, salePartner, false);
        String attribute = gameAttribute.getString("attribute");
        List<InterAttrRes> interAttrResList = new ArrayList<>();
        if (StringUtils.isNotEmpty(attribute)) {
            List<JSONObject> jsonObjects = JSONObject.parseArray(attribute, JSONObject.class);
            for (JSONObject jsonObject : jsonObjects) {
                String fieldType = jsonObject.getString("fieldType");
                boolean request = jsonObject.getBoolean("isMandatory");
                if (StringUtils.equals("1", type)) {
                    if (fieldType.equals("2")) {
                        InterAttrRes interAttrRes = new InterAttrRes();
                        interAttrRes.setId(jsonObject.getString("fieldIdentification"));
                        interAttrRes.setName(jsonObject.getString("fieldName"));
                        interAttrRes.setUuid(UuidUtils.generateUuid());
                        interAttrRes.setRequired(request);
                        String radioJsonStr = jsonObject.getString("dictValue");
                        if (StringUtils.isNotEmpty(radioJsonStr)) {
                            List<InterAttrRes> radioInterAttrResList = new ArrayList<>();
                            List<JSONObject> radioJsonList = JSONObject.parseArray(radioJsonStr, JSONObject.class);
                            for (JSONObject radioJson : radioJsonList) {
                                InterAttrRes radioInterAttrRes = new InterAttrRes();
                                radioInterAttrRes.setId(radioJson.getString("dictCode"));
                                radioInterAttrRes.setName(radioJson.getString("dictValue"));
                                radioInterAttrRes.setUuid(UUID.randomUUID().toString());
                                radioInterAttrResList.add(radioInterAttrRes);
                            }
                            interAttrRes.setInterServerRes(radioInterAttrResList);
                        }
                        interAttrResList.add(interAttrRes);
                    }
                } else if (StringUtils.equals("2", type)) {
                    if (fieldType.equals("1")) {
                        InterAttrRes interAttrRes = new InterAttrRes();
                        interAttrRes.setId(jsonObject.getString("fieldIdentification"));
                        interAttrRes.setName(jsonObject.getString("fieldName"));
                        interAttrRes.setUuid(UuidUtils.generateUuid());
                        interAttrRes.setRequired(request);
                        String radioJsonStr = jsonObject.getString("dictValue");
                        if (StringUtils.isNotEmpty(radioJsonStr)) {
                            List<InterAttrRes> checkInterAttrResList = new ArrayList<>();
                            List<JSONObject> checkJsonList = JSONObject.parseArray(radioJsonStr, JSONObject.class);
                            for (JSONObject checkJson : checkJsonList) {
                                InterAttrRes checkInterAttrRes = new InterAttrRes();
                                checkInterAttrRes.setId(checkJson.getString("dictCode"));
                                checkInterAttrRes.setName(checkJson.getString("dictValue"));
                                checkInterAttrRes.setUuid(UUID.randomUUID().toString());
                                checkInterAttrResList.add(checkInterAttrRes);
                            }
                            interAttrRes.setInterServerRes(checkInterAttrResList);
                        }
                        interAttrResList.add(interAttrRes);
                    }
                } else if (StringUtils.equals("3", type)) {
                    if (fieldType.equals("3")) {
                        InterAttrRes interAttrRes = new InterAttrRes();
                        interAttrRes.setId(jsonObject.getString("fieldIdentification"));
                        interAttrRes.setName(jsonObject.getString("fieldName"));
                        interAttrRes.setUuid(UuidUtils.generateUuid());
                        interAttrRes.setRequired(request);
                        interAttrResList.add(interAttrRes);
                    }
                }
            }
            if (type.equals("1"))
                getIsFaceAndAntiAddiction(gameId, salePartner, interAttrResList);
        }
        return interAttrResList;
    }

    /**
     * 获取人脸识别以及防沉迷选项
     *
     * @param gameId
     * @param salePartner
     */
    private void getIsFaceAndAntiAddiction(String gameId, SalePartner salePartner, List<InterAttrRes> interAttrResList) {
        String isFace = HttpRequest.get("https://www.xizai.com/trade/system/dict/data/type/sfrlsb")
                .header("authorization", salePartner.getTwoOther())
                .execute()
                .body();
        boolean isTrue = replaceToken(salePartner, isFace);
        if (isTrue) getIsFaceAndAntiAddiction(gameId, salePartner, interAttrResList);
        if (StringUtils.isNotEmpty(isFace)) {
            JSONObject isFaceJson = JSONObject.parseObject(isFace);
            if (isFaceJson.getString("code").equals("200")) {
                List<JSONObject> isFaceDataList = JSONObject.parseArray(isFaceJson.getString("data"), JSONObject.class);
                InterAttrRes interAttrRes = new InterAttrRes();
                interAttrRes.setId("isFace");
                if (gameId.equals("2"))
                    interAttrRes.setName("");
                else interAttrRes.setName("是否能更改人脸");
                interAttrRes.setRequired(true);
                interAttrRes.setUuid(UUID.randomUUID().toString());
                List<InterAttrRes> radioInterAttrResList = new ArrayList<>();
                for (JSONObject isFaceData : isFaceDataList) {
                    InterAttrRes radioInterAttrRes = new InterAttrRes();
                    radioInterAttrRes.setId(isFaceData.getString("dictCode") + "&" + isFaceData.getString("dictValue"));
                    radioInterAttrRes.setName(isFaceData.getString("dictLabel"));
                    radioInterAttrRes.setUuid(UUID.randomUUID().toString());
                    radioInterAttrResList.add(radioInterAttrRes);
                }
                interAttrRes.setInterServerRes(radioInterAttrResList);
                interAttrResList.add(interAttrRes);
            }
        }
        if (!gameId.equals("2")) {
            String antiAddiction = HttpRequest.get("https://www.xizai.com/trade/system/dict/data/type/anti_addiction")
                    .header("authorization", salePartner.getTwoOther())
                    .execute()
                    .body();
            boolean is_true = replaceToken(salePartner, isFace);
            if (is_true) getIsFaceAndAntiAddiction(gameId, salePartner, interAttrResList);
            if (StringUtils.isNotEmpty(antiAddiction)) {
                JSONObject antiAddictionJson = JSONObject.parseObject(antiAddiction);
                if (antiAddictionJson.getString("code").equals("200")) {
                    List<JSONObject> isFaceDataList = JSONObject.parseArray(antiAddictionJson.getString("data"), JSONObject.class);
                    InterAttrRes interAttrRes = new InterAttrRes();
                    interAttrRes.setId("antiAddiction");
                    interAttrRes.setName("防沉迷");
                    interAttrRes.setRequired(true);
                    interAttrRes.setUuid(UUID.randomUUID().toString());
                    List<InterAttrRes> radioInterAttrResList = new ArrayList<>();
                    for (JSONObject isFaceData : isFaceDataList) {
                        InterAttrRes radioInterAttrRes = new InterAttrRes();
                        radioInterAttrRes.setId(isFaceData.getString("dictCode") + "&" + isFaceData.getString("dictValue"));
                        radioInterAttrRes.setName(isFaceData.getString("dictLabel"));
                        radioInterAttrRes.setUuid(UUID.randomUUID().toString());
                        radioInterAttrResList.add(radioInterAttrRes);
                    }
                    interAttrRes.setInterServerRes(radioInterAttrResList);
                    interAttrResList.add(interAttrRes);
                }
            }
        }
    }


    private JSONObject getGameAttribute(String gameId, SalePartner salePartner, boolean isServer) {
        String categoryAttribute = HttpRequest.get("https://www.xizai.com/trade/account/category/getCategoryAttribute/" + gameId)
                .header("authorization", salePartner.getTwoOther())
                .execute()
                .body();
        boolean isTrue = replaceToken(salePartner, categoryAttribute);
        if (isTrue) getGameAttribute(gameId, salePartner, isServer);
        JSONObject categoryAttributeJson = JSONObject.parseObject(categoryAttribute);
        String categoryAttributeCode = categoryAttributeJson.getString("code");
        JSONObject resultJson = new JSONObject();
        if (categoryAttributeCode.equals("0")) {
            String categoryAttributeListStr = categoryAttributeJson.getString("list");
            List<JSONObject> categoryAttributeList = JSONObject.parseArray(categoryAttributeListStr, JSONObject.class);
            if (ObjectUtil.isNotEmpty(categoryAttributeList)) {
                for (JSONObject attribute : categoryAttributeList) {
                    if (isServer) {
                        if (attribute.getString("fieldName").contains("客户端")) {
                            resultJson.put("system", attribute);
                        } else if (attribute.getString("fieldName").contains("服务器")) {
                            if (!resultJson.containsKey("fuwuqi")) {
                                resultJson.put("fuwuqi", attribute);
                            } else {
                                JSONObject fuwuJson = resultJson.getJSONObject("fuwuqi");
                                fuwuJson.put("children", attribute);
                            }
                        }
                    } else {
                        boolean isContains = categoryAttributeList.removeIf(name -> name.getString("fieldName").contains("客户端") || name.getString("fieldName").contains("服务器"));
                        if (isContains) {
                            resultJson.put("attribute", categoryAttributeList);
                            break;
                        }
                    }
                }
            }
        }
        return resultJson;
    }

    private boolean replaceToken(SalePartner salePartner, String resultMsg) {
        JSONObject resultMsgJson = JSONObject.parseObject(resultMsg);
        if (resultMsgJson.getString("msg").contains("认证失败，无法访问系统资源")) {
            String tokenBody = HttpRequest.get("http://jym.maimaizhanghao.com:7589/xizai?uname=" + salePartner.getSaleKey() + "&pwd=" + salePartner.getOther())
                    .execute().body();
            JSONObject tokenJsonObject = JSONObject.parseObject(tokenBody);
            String token = tokenJsonObject.getString("token");
            if (StringUtils.isNotEmpty(token)) {
                salePartner.setTwoOther(token);
                salePartnerMapper.updateSalePartner(salePartner);
                return true;
            }
        }
        return false;
    }

    static String getAtta(String fieldDictType) {
        Map<String, Object> param = new HashMap<>();
        String url = "https://www.xizai.com/trade/goodsApi/queryGameField";
        param.put("field_dict_type", fieldDictType);
        String response = HttpUtils.doPostForm(url, param, null);
        return response;
    }
}
